package com.chaos.auth.service.userdetails;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.chaos.auth.api.constant.CommonConstant;
import com.chaos.auth.api.data.TUserData;
import com.chaos.auth.api.dto.userdetails.UserUserDetails;
import com.chaos.auth.config.enums.AuthenticationIdentityEnums;
import com.chaos.auth.api.dto.RegisterDto;
import com.chaos.auth.exception.AliOpenIdNotFoundException;
import com.chaos.auth.service.TUserService;
import com.chaos.auth.service.auth.BaseUserDetailsService;
import com.chaos.framework.model.enums.ResultEnum;
import com.chaos.framework.model.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author yjp
 * @date 2024/5/30
 */
@Slf4j
@Component
public class UserByAliOpenIdDetailsService implements BaseUserDetailsService {

    @Resource
    private TUserService userService;

    @Value("${alipay.appid:}")
    private String appId;

    @Override
    public UserDetails loadUserByAliOpenId(String aliOpenIdCode, Long tenantId) throws AliOpenIdNotFoundException {

//        try {
//            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
//            // 构造请求参数以调用接口
//            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
//            request.setGrantType("authorization_code");
//            request.setCode(code);
//            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
//            if (!response.isSuccess()) {
//                throw new BusinessException(ResultEnum.INTERNAL_SERVER_ERROR.getCode(), response.getMsg());
//            }
//            openId = response.getOpenId();
//        } catch (Exception e) {
//            log.error("支付宝登录失败,异常原因:{}", e.getMessage(), e);
//            throw new BusinessException(ResultEnum.INTERNAL_SERVER_ERROR.getCode(), "支付宝登录失败");
//        }

        String openId = "";
        TUserData queryData = TUserData.builder().aliOpenId(openId).build();
        List<TUserData> userDatas = userService.selectByData(queryData);
        TUserData userData = null;
        if (ObjectUtil.isEmpty(userDatas)) {
            //userData = (TUserData) register(registerDto);
        } else {
            userData = userDatas.get(0);
        }

        UserUserDetails userDetails = new UserUserDetails(userData);
        if (!userDetails.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        }
        userDetails.setAuthenticationIdentity(AuthenticationIdentityEnums.LogInIdentity.USER_ALIOPENID.getCode());
        return userDetails;
    }

    private AlipayConfig getAlipayConfig() {
        AlipayConfig alipayConfig = new AlipayConfig();
        try {
            String privateKey = getKey(CommonConstant.PRIVATE_PATH); //"<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->";
            String alipayPublicKey = getKey(CommonConstant.PUBLIC_PATH);//"<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->";
            log.info("privateKey:{},publicPath:{}", privateKey, alipayPublicKey);
            alipayConfig.setAppId(appId);
            alipayConfig.setPrivateKey(privateKey);
//        alipayConfig.setFormat("json");
            alipayConfig.setAlipayPublicKey(alipayPublicKey);
            alipayConfig.setCharset("UTF-8");
            alipayConfig.setSignType("RSA2");
            log.info("支付宝配置类读取:{}", JSONObject.toJSONString(alipayConfig));
        } catch (Exception e) {
            log.error("读取支付宝配置异常", e);
        }
        return alipayConfig;
    }


    private String getKey(String path) {
        InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
        StringBuilder resultStringBuilder = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(resourceAsStream))) {
            String line;
            while ((line = br.readLine()) != null) {
                resultStringBuilder.append(line).append("\n");
            }
            log.info("resultStringBuilder:{}", resultStringBuilder.toString());
            return resultStringBuilder.toString();
        } catch (IOException e) {
            log.info("读取文件流异常:{}", e);
        }
        return null;
    }


}
